<template>
  <div>
    <el-dialog
      custom-class="google-customer-info-dialog"
      :width="tableWidth"
      destroy-on-close
      append-to-body
      :visible.sync="show"
      :before-close="cancel"
    >
      <template #title>
        <div style="display: flex; align-items: center; justify-content: space-between; margin-right: 40px">
          <div>{{ $t('客户信息') }}</div>
          <div style="color: #13ce66; cursor: pointer" @click="handleNavigation">{{ $t('导航去这里') }}</div>
          <div></div>
        </div>
      </template>
      <el-form @submit.native.prevent ref="formRef" :model="formData" size="mini" label-width="80px">
        <el-form-item label="客人:" prop=""> {{ formData.receiveName }} </el-form-item>
        <el-form-item label="邮编:" prop=""> {{ formData.receivePostcode }} </el-form-item>
        <el-form-item label="地址:" prop="">
          <a
            :style="{
              color: formData.historyOrderImageArr && formData.historyOrderImageArr.length ? 'blue' : '',
            }"
            @click="handleHistory"
          >
            {{ formData.address }}
          </a>
        </el-form-item>
        <el-form-item label="电话:" prop=""> {{ formData.receivePhone }} </el-form-item>
        <el-form-item label="包裹号:" prop=""> {{ formData.packageNo }} </el-form-item>
        <el-form-item label="状态:" prop="">
          <!-- 1 待配送 2 配送中 3 已完成 (状态2 无用) -->
          <div v-if="formData.status == 1" :style="{ color: $randomColor(formData.status) }">{{ $t('待配送') }}</div>
          <div v-if="formData.status == 2" :style="{ color: $randomColor(formData.status) }">{{ $t('配送中') }}</div>
          <div v-if="formData.status == 3" :style="{ color: $randomColor(formData.status) }">{{ $t('已完成') }}</div>
        </el-form-item>
        <el-form-item label="拍照确认:">
          <div class="camera-upload" ref="cameraUploadRef">
            <!-- 已完成&不是扫码送达才禁用上传 -->
            <el-upload
              :disabled="formData.status == 3 && formData.isScanDelivery == 0"
              action=""
              :limit="10"
              :file-list="fileList"
              :auto-upload="false"
              :on-change="handleUpload"
              ref="uploadRef"
              list-type="picture-card"
              capture="camera"
              accept="image/*"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="$viewImage(file.url)">
                    <i class="el-icon-view"></i>
                  </span>
                  <span class="el-upload-list__item-delete" v-if="formData.status != 3" @click="handleOnRemove(file)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="负责人:" prop="">
          {{ formData.nickNames }}
        </el-form-item>
        <!-- 已完成就不显示扫码了 -->
        <el-form-item v-if="formData.status != 3" label="扫码送达:" prop="">
          <el-button
            v-hasPermi="['distribution:googleRouteBatch:scanDelivery']"
            style="font-size: 15px; font-weight: bold"
            type="text"
            @click="handleScan"
          >
            扫码
          </el-button>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <div>
          <!-- 判断是确认送达还是扫码送达 -->
          <el-button
            v-show="!formData.isScanDelivery"
            @click="handleSubmit"
            type="success"
            :disabled="formData.status == 3"
            v-hasPermi="['distribution:googleRouteShipments:confirmShipment']"
          >
            {{ $t('确认送达') }}
          </el-button>
          <el-button
            v-show="formData.isScanDelivery"
            @click="handleSanDeliverySavePic"
            type="success"
            v-hasPermi="['distribution:googleRouteBatch:scanDeliverySavePic']"
          >
            {{ $t('扫码送达') }}
          </el-button>
          <el-button @click="cancel">
            {{ $t('关闭') }}
          </el-button>
        </div>
      </div>
    </el-dialog>
    <History :show.sync="history.show" :formData="history.formData" />
  </div>
</template>

<script>
import request from '@/utils/request'
import { confirmShipment, scanDelivery, scanDeliverySavePic, queryByIdDetails } from '@/api/orderManage/myDispatch'
import History from './history.vue'

export default {
  components: { History },

  props: {
    /**
     * formData
     */
    formData: {
      type: Object,
      default: () => ({}),
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      /**导航位置 */
      endAddress: '',
      code: '',
      history: { show: false, formData: {} },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        key1: [{ required: true, message: this.$t('请输入'), trigger: 'blur' }],
      },
      fileList: [],
      /**是否正在上传 */
      uploadFlag: false,
      /**待上传列表 */
      waitUploadList: [],
      uploadLoading: false,
    }
  },
  computed: {
    /**@returns {any} */
    tableWidth() {
      return this.isMobile() ? '350px' : '600px'
    },
  },
  mounted() {
    document.documentElement.style.setProperty('--google-confirm-delivery-width', this.isMobile() ? '70%' : '420px')
  },
  watch: {
    show: function (newValue) {
      if (newValue) {
        const { lat, lng } = this.formData.path[this.formData.path.length - 1]
        this.endAddress = `${lat()},${lng()}`
        this.getList()
      }
    },
  },
  methods: {
    getList() {
      queryByIdDetails(this.formData.id).then((res) => {
        Object.keys(this.formData).forEach((key) => {
          this.formData[key] = res.data[key]
        })
        if (this.formData.sendConfirmImages) {
          this.fileList = this.formData.sendConfirmImages?.split(',').map((i) => {
            return {
              url: i,
            }
          })
        } else {
          this.fileList = []
        }
      })

      this.$nextTick(() => {
        this.$refs['cameraUploadRef'].children[0].children[1].children[1].setAttribute('capture', 'camera')
      })
    },

    handleSanDeliverySavePic() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          this.$confirm(this.$t('确认送达?'), this.$t('提示'), {
            type: 'warning',
            customClass: 'google-confirm-delivery',
          }).then(() => {
            const data = {
              id: this.formData.id,
              imageArr: this.$refs['uploadRef'].uploadFiles.map((i) => i.url),
            }
            scanDeliverySavePic(data).then((res) => {
              const { code, data, msg } = res
              if (code === 200) {
                this.$message({ type: 'success', message: msg })
                this.getList()
              }
            })
          })
        }
      })
    },
    handleScan() {
      this.$scanQrCode().$on('code', (code) => {
        this.code = code
        const data = {
          id: this.formData.id,
          packageNo: code,
        }
        scanDelivery(data).then((res) => {
          const { code, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })
            this.getList()
          }
        })
      })
    },
    handleHistory() {
      if (this.formData.historyOrderImageArr && this.formData.historyOrderImageArr.length) {
        this.history.show = true
        this.history.formData = { ...this.formData }
      }
    },
    /**导航 */
    handleNavigation() {
      // Try HTML5 geolocation.
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const startAddress = `${position.coords.latitude},${position.coords.longitude}`

            const url =
              'https://www.google.com/maps/dir/?api=1&origin=' +
              startAddress +
              '&destination=' +
              this.endAddress +
              '&travelmode=driving'
            console.log(`url ==>`, JSON.parse(JSON.stringify(url)))
            window.open(url, '_blank')
          },
          (error) => {
            this.$message({ type: 'error', message: error.message })
          },
        )
      }
    },

    uploadImg(data) {
      return request({
        url: '/system/oss/uploadTemp',
        method: 'post',
        data,
        repetitiveConfig: {
          neglectful: true,
          interval: 3000,
        },
      })
    },
    // 上传单个文件
    uploadSingleFile() {
      /**上传结束 */
      if (!this.waitUploadList.length) {
        // 正在上传状态改为false
        this.uploadFlag = false
        this.uploadLoading?.close()
        this.$message({ type: 'success', message: '上传完成!' })
        return
      }
      const formData = new FormData()
      const file = this.waitUploadList.shift()
      formData.append('file', file.raw)
      formData.append('type', '12')
      formData.append('businessId', this.formData.id)
      this.uploadImg(formData)
        .then((res) => {
          const index = this.$refs['uploadRef'].uploadFiles.findIndex((i) => i.uid == file.uid)
          if (index > -1) {
            this.$refs['uploadRef'].uploadFiles[index].url = res.data.url
          }
        })
        .finally(() => this.uploadSingleFile())
    },
    handleUpload(file) {
      // 如果正在上传中，直接添加到待上传列表中
      if (this.uploadFlag) {
        return this.waitUploadList.push(file)
      }
      this.uploadLoading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      this.uploadFlag = true
      this.waitUploadList = [file]
      this.uploadSingleFile()
    },
    handleOnRemove(file) {
      const index = this.$refs['uploadRef'].uploadFiles.findIndex((f) => f.uid == file.uid)
      if (index > -1) {
        this.$refs['uploadRef'].uploadFiles.splice(index, 1)
      }
    },

    handleSubmit() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          this.$confirm(this.$t('确认送达?'), this.$t('提示'), {
            type: 'warning',
            customClass: 'google-confirm-delivery',
          }).then(() => {
            const data = {
              id: this.formData.id,
              imageArr: this.$refs['uploadRef'].uploadFiles.map((i) => i.url),
            }
            confirmShipment(data).then((res) => {
              const { code, data, msg } = res
              if (code === 200) {
                this.$message({ type: 'success', message: msg })
                this.cancel()
                this.$emit('getList')
              }
            })
          })
        }
      })
    },
    cancel() {
      this.$emit('update:show', false)
      this.$emit('getList')
    },
  },
}
</script>
<style lang="scss" scoped>
.camera-upload {
  width: 100%;
  max-height: 300px;
  overflow: auto;
  $itemWidth: 110px;
  ::v-deep .el-upload-list__item {
    width: $itemWidth;
    height: $itemWidth;
  }
  ::v-deep .el-upload--picture-card {
    width: $itemWidth;
    height: $itemWidth;
    position: relative;
    .el-icon-plus {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
</style>
